package model.primary

import java.sql.Timestamp
import java.time.Instant

import model.exceptions.{AbstractBusinessException, ErrorCode}
import model.vo.{StandardFailureResponse, StandardSuccessResponse}
import play.api.libs.json.Json
import play.api.mvc
import play.api.mvc.{AbstractController, AnyContent, ControllerComponents}

import scala.concurrent.{ExecutionContext, Future}

abstract class SwiftController(private val cc: ControllerComponents)(
  implicit ec: ExecutionContext
) extends AbstractController(cc) {
  implicit def makeSuccessAPIVO2ActionAsync(
    successVOFutureCallback: () => Future[StandardSuccessResponse]
  ): mvc.Action[AnyContent] = Action.async {
    val startTime = System.currentTimeMillis()
    val responseTime = Some(Timestamp.from(Instant.now()))
    successVOFutureCallback()
      .map(
        result =>
          result.copy(
            responseTime = responseTime,
            duringTime = Some(System.currentTimeMillis() - startTime)
        )
      )
      .map(result => Ok(Json.toJson(result).toString))
      .recover {
        case abe: AbstractBusinessException =>
          val res = StandardFailureResponse(abe.errorCode, abe.msg)
          Ok(Json.toJson(res).toString)
        case e: Exception =>
          val res = StandardFailureResponse(
            ErrorCode.CAN_NOT_PROCESS_ERROR,
            e.getMessage
          )
          Ok(Json.toJson(res).toString)
      }
  }
}
